﻿using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;

namespace Callisto.Infrastructure.Resourcing
{
    public class ResourceProvider : IResourceProvider
    {
        #region Fields
        private readonly Assembly _resourceAssembly;
        private readonly string _resourceBaseName;
        private ResourceManager _resourceManager;
        #endregion Fields

        #region Ctor
        public ResourceProvider(Assembly resourceAssembly, string resourceBaseName)
        {
            if (resourceAssembly == null)
                throw new ArgumentNullException("resourceAssembly");
            if(resourceBaseName == null)
                throw new ArgumentNullException("resourceBaseName");
            if (resourceBaseName == string.Empty)
                throw new ArgumentException("resourceBaseName");

            _resourceAssembly = resourceAssembly;
            _resourceBaseName = resourceBaseName;
        }
        #endregion Ctor

        #region Methods
        public T GetValue<T>(string resourceKey)
        {
            return GetValue<T>(resourceKey, CultureInfo.InvariantCulture);
        }

        public T GetValue<T>(string resourceKey, CultureInfo ci)
        {
            var resourceManager = GetResourceManager();
            if (resourceManager == null)
                return default(T);
            else
                return (T)resourceManager.GetObject(resourceKey, ci);
        }

        private ResourceManager GetResourceManager()
        {
            if (_resourceManager != null)
                return _resourceManager;

            var resourceName = _resourceAssembly.GetManifestResourceNames()
                .FirstOrDefault(x => x.Contains(_resourceBaseName));

            if (string.IsNullOrEmpty(resourceName))
                return null;

            _resourceManager = new ResourceManager(resourceName.Replace(".resources", ""), _resourceAssembly);
            return _resourceManager;
        }
        #endregion Methods
    }
}
